package com.carcontrol.rotate;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.carcontrol.rotate.base.BaseActivity;
import com.carcontrol.rotate.base.BaseApplication;
import com.carcontrol.rotate.bean.PageS;
import com.carcontrol.rotate.util.IntentUtils;
import com.carcontrol.rotate.util.SharedPreferencesUrls;
import com.carcontrol.rotate.util.ToastUtil;
import com.carcontrol.rotate.util.Util_Rotate3DAnimation2;
import com.carcontrol.rotate.utils.CRC16;
import com.carcontrol.rotate.utils.TransformUtils;
import com.dalong.library.listener.OnItemSelectedListener;
import com.dalong.library.listener.OnLoopViewTouchListener;
import com.dalong.library.view.LoopRotarySwitchView;
import com.easy.carpanel.uart.uartJni;
import com.monkey.miclockview.MiClockView;
import com.monkey.miclockview.SpeedView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

//首页、启动页
@SuppressLint("NewApi")
public class MainActivity extends BaseActivity {

    private FrameLayout v;  //整个界面的Layout
    private Activity activity;  //用于界面跳转

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");  //时间格式 时:分
    private SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy/MM/dd");    //日期格式 年/月/日

    private long loopTime = 1 * 100;  //时间显示间隔   默认1分钟
    private int cn = 10*60*10;     //屏保显示间隔   默认10分钟

//    private long loopTime = 10 * 100;  //时间显示间隔   默认1分钟
//    private int cn = 1;     //屏保显示间隔   默认10分钟

    private FrameLayout framelayout;    //旋转时当前界面的Layout
    private FrameLayout framelayout2;    //旋转时目的界面的Layout

    float dx;   //用于界面旋转的触摸横向移动量
    float x;    //导航栏按下时的横向坐标

    boolean first = true;   //是否第一次按下
    boolean isEnd = false;  //手指是否抬起

    private float degrees;  //当前界面旋转角度
    private float degrees2;  //目的界面旋转角度

    int pos;    //item位置id

    int id = 1; //旋转起始界面所在framelayout的id
    int id2 = 2; //旋转目的界面所在framelayout的id

    //获取屏幕分辨率
    int width = BaseApplication.width;  //宽
    int height = BaseApplication.height;    //高
    float density = BaseApplication.density;    //密度

    boolean left_first = true;  //是否刚开始旋转
    public static boolean isStop = false;   //旋转是否停止
    public static int curPos;   //当前界面id

    Handler handler = new Handler();

    private TextView tv_temp;   //温度控件
    private TextView tv_time;   //时间控件
    private TextView tv_date;   //日期控件

    private MiClockView miClockView;    //屏保界面
    private SpeedView speedView;    //码表界面

    private Fragment fromFrag;  //起始界面类
    private Fragment toFrag;  //目的界面类

    private int toPos;  //目的界面id
    private int toPos2;  //目的界面id2

    private Fragment[] frags;   //界面类数组

    public static String[] names;   //导航栏item名字数组

    private Object[] allParam;  //控件参数数组

    private byte[] bytes_temp;  //读取温度串口指令

    private com.carcontrol.rotate.bean.PageS PageS = new PageS();

    private String svCmd;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        v = new FrameLayout(this);
        setContentView(v);

//        DisplayMetrics metrics = new DisplayMetrics();
//        WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
//        wm.getDefaultDisplay().getMetrics(metrics);
//        density = BaseApplication.density = metrics.density;
//        width = BaseApplication.width = metrics.widthPixels;
//        height = BaseApplication.height = metrics.heightPixels;
//
//        Log.e("BaseApplication===", density+"==="+width+"==="+height);

//        try {
//            packageName = getPackageName();
//            packageInfo = getPackageManager().getPackageInfo(packageName, 0);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        TvView tv = new TvView(this);
//        tv.ru

        context = this;
        activity = this;

        Log.e("ma===onCreate", width+"==="+height+"==="+density);

        PageS.feedType.put("b003", "1");    //氛围灯
        PageS.feedType.put("d001", "1");    //照明灯
        PageS.feedType.put("f003", "1");    //净化器
        PageS.feedType.put("f004", "1");    //多媒体
        PageS.feedType.put("6001", "1");    //温度
        PageS.feedType.put("6002", "1");    //风速
        PageS.feedType.put("6003", "1");    //码表
        PageS.feedType.put("9001", "1");    //天窗开
        PageS.feedType.put("9002", "1");    //天窗关
        PageS.feedType.put("9003", "1");    //天窗帘开
        PageS.feedType.put("9004", "1");    //天窗帘关
        PageS.feedType.put("1010", "1");    //主电压
        PageS.feedType.put("1011", "1");    //副电压

        //2e100aeb000000ffffff3f00714d
        byte b1 = getCheckCanboxByte(new byte[]{0x2e, (byte)0x10, 0x0A, (byte)0xeb, 0x00, 0x00, 0x00, (byte)0xff, (byte)0xff, (byte)0xff, 0x3f, 0x00, (byte) 0x71});
        Log.e("onReceive===@", "===" + b1);

//        addDataReceiver();  //can总线 新版串口反馈  TODO


        names = (String[]) SharedPreferencesUrls.getInstance().getObject("names");   //读取内部存储器：导航转盘的item名字数组

        Log.e("ma===onResume", width+"==="+height+"==="+names);

        if(names==null){    //如果item名字数组为空用默认值，即"灯光", "码表", "净化器", "天窗", "多媒体", "空调"
            names = Config.names;
        }else{
            Log.e("ma===onResume2", width+"==="+height+"==="+names.length+"==="+Config.mapTab.size());
        }

        //根据item名字获取Fragment——每个显示区对应的类
        frags = new Fragment[names.length];
        for (int i = 0; i < names.length; i++) {
            frags[i] = Config.mapTab.get(names[i]);
        }

        Log.e("ma===onResume3", width+"==="+height+"==="+names.length+"==="+frags.length+"==="+frags[0]);


        //界面所有控件的参数object数组，采用Object嵌套object思想，每个子object数组是各种控件，object数组可以放各种类型的参数，有"iv"——String型(控件类型)、Rect——java自带对象(控件大小位置)、R.mipmap.bg——int型(控件资源id)、false——boolean型（控件能否点击）、byte[]——数组型（控件点击后发送的串口指令）等
        //iv——图片: 控件类型、控件大小位置、图片资源id、能否点击、点击后发送的指令；
        //tv——文字: 控件类型、控件大小位置、名字、字体大小、字体颜色；
        //lrsv——导航转盘: 控件类型、控件大小位置、item名字数组、字体大小、字体颜色；
        //fl——显示区: 控件类型、控件大小位置、item名字数组、字体大小、字体颜色；
        //mcv——小米时钟屏保界面: 控件类型、控件大小位置、名字、字体大小、界面背景颜色、时钟背景图片资源id、秒针图片资源id、分针图片资源id、时针图片资源id、圆心图片资源id
        allParam = new Object[]{
                //全背景
                new Object[]{"iv", new Rect(0*width/width0, 0*height/height0, 1280*width/width0, 480*height/height0), R.mipmap.bg, false, ""},
//                //左背景
//                new Object[]{"iv", new Rect(0*width/width0, 0*height/height0, 232*width/width0, 480*height/height0), R.mipmap.bg_left, false, ""},
                //右背景
                new Object[]{"iv", new Rect(475*width/width0, 85*height/height0, 483*width/width0, 30*height/height0), R.mipmap.bg_top, false, ""},

//                //导航菜单
//                new Object[]{"iv", new Rect(67*width/width0, 79*height/height0, 93*width/width0, 32*height/height0), R.mipmap.menu_navi_off, true, "com.autonavi.amapauto"},
////                //投屏菜单
////                new Object[]{"iv", new Rect(68*width/width0, 123*height/height0, 94*width/width0, 32*height/height0), R.mipmap.menu_tscreen_off, true, "com.hpplay.happyplay.aw"},
////                //视频菜单
////                new Object[]{"iv", new Rect(73*width/width0, 184*height/height0, 94*width/width0, 32*height/height0), R.mipmap.menu_vedio_off, true, "hdpfans.com"},
//                //音乐菜单
//                new Object[]{"iv", new Rect(70*width/width0, 162*height/height0, 95*width/width0, 32*height/height0), R.mipmap.menu_music_off, true, "com.netease.cloudmusic"},
//                //天气菜单
//                new Object[]{"iv", new Rect(76*width/width0, 245*height/height0, 94*width/width0, 32*height/height0), R.mipmap.menu_weather_off, true, "sina.mobile.tianqitongtv"},
//                //浏览器菜单
//                new Object[]{"iv", new Rect(51*width/width0, 328*height/height0, 114*width/width0, 32*height/height0), R.mipmap.menu_browser_off, true, "com.tencent.mtt"},
//                //应用菜单
//                new Object[]{"iv", new Rect(68*width/width0, 411*height/height0, 92*width/width0, 32*height/height0), R.mipmap.menu_application_off, true, ""},


                //旋转菜单
                new Object[]{"lrsv", new Rect(407*width/width0, 40*height/height0, 655*width/width0, 110*height/height0), names, 24, Color.WHITE},
                //主显示区
                new Object[]{"fl", new Rect(246*width/width0, 140*height/height0, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)},

//                new Object[]{"tv", new Rect(27*width/width0, 20*height/height0, 0, 0), "温度", 18, 0xFF4785E2, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
                //时间
                new Object[]{"tv", new Rect(1032*width/width0, 19*height/height0, 0, 0), "时间", 18, 0xFF4785E2, false},
                //日期
                new Object[]{"tv", new Rect(1145*width/width0, 28*height/height0, 0, 0), "日期", 10, 0xFF4785E2, false},
//                new Object[]{"tv", new Rect(1240*width/width0, 19*height/height0, 0, 0), "UI定制", 18, Color.GREEN, true},

//                new Object[]{"tv", new Rect(64*width/width0, 90*height/height0, 0, 0), "投屏", 19, Color.WHITE, true},
//                new Object[]{"tv", new Rect(76*width/width0, 150*height/height0, 0, 0), "视频", 19, Color.WHITE, true},
//                new Object[]{"tv", new Rect(90*width/width0, 210*height/height0, 0, 0), "音乐", 19, Color.WHITE, true},
//                new Object[]{"tv", new Rect(91*width/width0, 270*height/height0, 0, 0), "蓝牙", 19, Color.WHITE, true},
//                new Object[]{"tv", new Rect(74*width/width0, 330*height/height0, 0, 0), "网络", 19, Color.WHITE, true},
//                new Object[]{"tv", new Rect(64*width/width0, 390*height/height0, 0, 0), "设置", 19, Color.WHITE, true},

//                new Object[]{"mcv", new Rect(0*width/width0, 0*height/height0, 1280*width/width0, 480*height/height0), "小米时钟", 19, Color.BLACK, R.mipmap.clock_bg, R.mipmap.needle_second, R.mipmap.needle_minute, R.mipmap.needle_hour, R.mipmap.open},
                //码表屏保界面
                new Object[]{"sv", new Rect(0*width/width0, 0*height/height0, 1280*width/width0, 480*height/height0), "码表", 19, Color.BLACK, R.mipmap.speed_bg, R.mipmap.speed_needle, R.mipmap.speed_center, "6003"},

        };

        initView(); //加载并显示界面

        loop(); //轮循 老版串口反馈    TODO
    }

    @Override
    protected void onResume() {
        super.onResume();


    }



    //加载并显示界面
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView(){
        for (int i=0; i<allParam.length; i++){
            Object[] obj = (Object[])allParam[i];   //获取allParam的每个元素，一个元素即为界面的一个控件
            Rect rect = (Rect)obj[1];   //获取控件的大小位置
            String type = (String)obj[0];   //获取控件的类型，有iv、tv、mcv、lrsv、fl等

            if("tv".equals(type)){  //TextView 加载文字
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);   //FrameLayout.LayoutParams.WRAP_CONTENT：表示包住文字的宽高
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);    //设置文字的文字left、top、right、bottom， 注：right、bottom没用

                String name = (String)obj[2];   //获取文字名字
                int textSize = (int)obj[3];     //获取文字大小
                int textColor = (int)obj[4];     //获取文字颜色
                TextView tv = new TextView(context);
                tv.setText(name);   //设置文字名字
                tv.setTextSize(textSize);   //设置文字大小
                tv.setTextColor(textColor);   //设置文字颜色
                v.addView(tv, params);  //添加并设置文字布局

                if("温度".equals(name)){
                    tv_temp = tv;   //提取出全局变量，用于轮循更新温度
                    bytes_temp = (byte[])obj[6];     //获取读取温度的串口指令
                    tv.setText(""); //设置温度的默认值为空

                    //点击时间显示屏保
                    tv_temp.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
//                            speedView.setmSpeed(120);
//                            speedView.setVisibility(View.VISIBLE);

                            Intent intent = new Intent("carcontrol.broadcast.action");
                            intent.putExtra("feedDevice", "d001");
                            intent.putExtra("feedStatus", "0001");
                            context.sendBroadcast(intent);
                        }
                    });
                }else if("时间".equals(name)){
                    tv_time = tv;   //提取出全局变量，用于轮循更新时间
                    tv.setText(""); //设置时间的默认值为空

                    //点击时间显示屏保
                    tv_time.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
//                            speedView.setmSpeed(120);
//                            speedView.setVisibility(View.VISIBLE);

                            Intent intent = new Intent("carcontrol.broadcast.action");
                            intent.putExtra("feedDevice", "f001");
                            intent.putExtra("feedStatus", "0001");
                            context.sendBroadcast(intent);
                        }
                    });
                }else if("日期".equals(name)){
                    tv_date = tv;   //提取出全局变量，用于轮循更新日期
                    tv.setText(""); //设置时间的默认值为空

                    //点击日期显示屏保
                    tv_date.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            speedView.setVisibility(View.VISIBLE);
//                            finish();
                        }
                    });
                }

                boolean isCanClick = (boolean)obj[5];

                //判断文字是否可点击，可点击才设置点击和触摸事件，并发送串口指令
                if(isCanClick){

                    //设置文字点击事件
                    tv.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {

                            Log.e("ma===tv", name+"===");

                            Intent intent = new Intent();
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            if("UI定制".equals(name)){
                                IntentUtils.startActivity(activity, SettingActivity.class);
//                                IntentUtils.startActivity(activity, LoginActivity.class);   //跳转到登录界面
                                finish();
                            }else if("投屏".equals(name)){

                                //1.百度地图包名 "com.baidu.BaiduMap";
                                //2.高德地图包名 "com.autonavi.minimap";
                                //3.腾讯地图包名 "com.tencent.map";
                                //4.谷歌地图包名  "com.google.android.apps.maps"
                                //5.高德地图车镜版本（后视镜）包名 "com.autonavi.amapautolite";
                                //6.高德地图车机版本包名  "com.autonavi.amapauto";

                                intent = getPackageManager().getLaunchIntentForPackage("com.autonavi.amapauto");   //跳转到高德地图车机版
                                startActivity(intent);
                            }else if("视频".equals(name)){
//                                Intent intent = new Intent(android.intent.action.VIEW);
                                intent.setAction(Intent.ACTION_VIEW);
//                                intent.setDataAndType(Uri.parse("file:///" + ""), "video/*");
//                                intent.setDataAndType(null, "video/*");
//                                localIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);

//                                intent.setType("video/*");
//                                startActivity(intent);

                                String path = Environment.getExternalStorageDirectory().getPath()+ "/1.mp4";//该路径可以自定义
                                File file = new File(path);
                                Uri uri = Uri.fromFile(file);
                                intent.setDataAndType(uri, "video/*");
                                startActivity(intent);     //跳转到视频界面

//                                Intent intent = new Intent(Intent.ACTION_VIEW);
//                                intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory() + "/3.mp4"), "video/mp4");
//                                startActivity(intent);
                            }else if("音乐".equals(name)){
                                intent.setAction(Intent.ACTION_VIEW);

                                String path = Environment.getExternalStorageDirectory().getPath()+ "/a.MP3";//该路径可以自定义
                                File file = new File(path);
                                Uri uri = Uri.fromFile(file);
                                intent.setDataAndType(uri, "audio/MP3");
                                startActivity(intent);     //跳转到音乐界面

//                                Intent it = new Intent(Intent.ACTION_VIEW);
//                                it.setDataAndType(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/a.MP3"), "audio/MP3");
//                                startActivity(it);


//                                intent.setAction(Intent.ACTION_PICK);
//                                intent.setDataAndType(Uri.EMPTY,"vnd.android.cursor.dir/playlist");
//                                intent.putExtra("withtabs", true); // 显示tab选项卡
//                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                                Intent j =Intent.createChooser(intent, "Choose an application to open with:");
//                                if (j == intent) {
//                                    startActivity(j);
//                                } else {
//                                    intent = new Intent("android.intent.action.MUSIC_PLAYER");
//                                    startActivity(intent);
//                                }
                            }else if("蓝牙".equals(name)){
                                intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                                startActivity(intent);     //跳转到蓝牙界面
                            }else if("网络".equals(name)){
//                                localIntent.setAction(Settings.ACTION_WIFI_SETTINGS);
                                intent.setAction(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
                                startActivity(intent);     //跳转到网络界面
                            }else if("设置".equals(name)){
                                intent.setAction(Settings.ACTION_SETTINGS);
//                                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                                startActivity(intent);     //跳转到设置界面
                            }

                        }
                    });
                }

            }else if("iv".equals(type)){    //ImageView 加载图片
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int imgSrc = (int)obj[2];   //获取图片资源id
                ImageView iv = new ImageView(context);
                iv.setImageResource(imgSrc);    //设置图片资源
                iv.setScaleType(ImageView.ScaleType.FIT_XY);   //拉伸图片到给定宽高
                v.addView(iv, params);

                boolean isCanClick = (boolean)obj[3];

                //判断图片是否可点击，可点击才设置点击和触摸事件，并发送串口指令
                if(isCanClick){

                    //图片点击事件
                    iv.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            int imgId = (int)obj[2];   //获取图片资源id
                            String cmd = (String)obj[4];   //获取该图片对应串口指令

                            Log.e("fragment_First===iv", imgId+"==="+cmd);

//                            if(imgId==R.mipmap.light){
//                                iv.setImageResource(R.mipmap.light_0);
//                                obj[2] = R.mipmap.light_0;
//                            }else if(imgId==R.mipmap.light_0){
//                                iv.setImageResource(R.mipmap.light);
//                                obj[2] = R.mipmap.light;
//                            }else if(imgId==R.mipmap.light_fw){
//                                iv.setImageResource(R.mipmap.light_fw_0);
//                                obj[2] = R.mipmap.light_fw_0;
//                            }else if(imgId==R.mipmap.light_fw_0){
//                                iv.setImageResource(R.mipmap.light_fw);
//                                obj[2] = R.mipmap.light_fw;
//                            }

//                            R.mipmap.menu_navi_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//                            R.mipmap.menu_tscreen_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//                            R.mipmap.menu_vedio_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//                            R.mipmap.menu_music_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//                            R.mipmap.menu_weather_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//                            R.mipmap.menu_browser_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//                            R.mipmap.menu_application_off, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},

                            //1.百度地图包名 "com.baidu.BaiduMap";
                            //2.高德地图包名 "com.autonavi.minimap";
                            //3.腾讯地图包名 "com.tencent.map";
                            //4.谷歌地图包名  "com.google.android.apps.maps"
                            //5.高德地图车镜版本（后视镜）包名 "com.autonavi.amapautolite";
                            //6.高德地图车机版本包名  "com.autonavi.amapauto";

                            if(event.getAction()==1) {

                                iv.setImageResource(imgId);

                                try {

                                    Log.e("ma===iv", "==="+imgId);

                                    Intent intent = new Intent();
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                    if (!"".equals(cmd)){
                                        intent = getPackageManager().getLaunchIntentForPackage(cmd);   //跳转到高德地图车机版
                                        startActivity(intent);

//                                        String s = "5aa50782600200070000";
//                                        readFeedback(s);
                                    }else{
                                        intent = new Intent(context, gActivity.class);
                                        startActivity(intent);
                                    }


//                                    if(imgId==R.mipmap.menu_navi_off){
//                                        intent = getPackageManager().getLaunchIntentForPackage("com.autonavi.amapauto");   //跳转到高德地图车机版
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu_tscreen_off){
//                                        intent = getPackageManager().getLaunchIntentForPackage("hdpfans.com");   //跳转到高德地图车机版
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu_vedio_off){
//                                        intent = getPackageManager().getLaunchIntentForPackage("hdpfans.com");   //跳转到高德地图车机版
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu_music_off){
//                                        intent = getPackageManager().getLaunchIntentForPackage("com.netease.cloudmusic");   //跳转到高德地图车机版
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu_weather_off){
//                                        intent = getPackageManager().getLaunchIntentForPackage("sina.mobile.tianqitongtv");   //跳转到高德地图车机版
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu_browser_off){
//                                        intent = getPackageManager().getLaunchIntentForPackage("com.android.chrome");   //跳转到高德地图车机版
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu_application_off){
////                                    intent = getPackageManager().getLaunchIntentForPackage("com.android.chrome");   //跳转到高德地图车机版
////                                    startActivity(intent);
//
//                                        intent = new Intent(context, gActivity.class);
//                                        startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu2_off){
////                                Intent intent = new Intent(android.intent.action.VIEW);
//                                        intent.setAction(Intent.ACTION_VIEW);
////                                intent.setDataAndType(Uri.parse("file:///" + ""), "video/*");
////                                intent.setDataAndType(null, "video/*");
////                                localIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
//
////                                intent.setType("video/*");
////                                startActivity(intent);
//
//                                        String path = Environment.getExternalStorageDirectory().getPath()+ "/1.mp4";//该路径可以自定义
//                                        File file = new File(path);
//                                        Uri uri = Uri.fromFile(file);
//                                        intent.setDataAndType(uri, "video/*");
//                                        startActivity(intent);     //跳转到视频界面
//
////                                Intent intent = new Intent(Intent.ACTION_VIEW);
////                                intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory() + "/3.mp4"), "video/mp4");
////                                startActivity(intent);
//                                    }else if(imgId==R.mipmap.menu3_off){
//                                        intent.setAction(Intent.ACTION_VIEW);
//
//                                        String path = Environment.getExternalStorageDirectory().getPath()+ "/a.MP3";//该路径可以自定义
//                                        File file = new File(path);
//                                        Uri uri = Uri.fromFile(file);
//                                        intent.setDataAndType(uri, "audio/MP3");
//                                        startActivity(intent);     //跳转到音乐界面
//
////                                Intent it = new Intent(Intent.ACTION_VIEW);
////                                it.setDataAndType(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/a.MP3"), "audio/MP3");
////                                startActivity(it);
//
//
////                                intent.setAction(Intent.ACTION_PICK);
////                                intent.setDataAndType(Uri.EMPTY,"vnd.android.cursor.dir/playlist");
////                                intent.putExtra("withtabs", true); // 显示tab选项卡
////                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
////
////                                Intent j =Intent.createChooser(intent, "Choose an application to open with:");
////                                if (j == intent) {
////                                    startActivity(j);
////                                } else {
////                                    intent = new Intent("android.intent.action.MUSIC_PLAYER");
////                                    startActivity(intent);
////                                }
//                                    }else if(imgId==R.mipmap.menu4_off){
//                                        intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
//                                        startActivity(intent);     //跳转到蓝牙界面
//                                    }else if(imgId==R.mipmap.menu5_off){
////                                localIntent.setAction(Settings.ACTION_WIFI_SETTINGS);
//                                        intent.setAction(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
//                                        startActivity(intent);     //跳转到网络界面
//                                    }else if(imgId==R.mipmap.menu6_off){
//                                        intent.setAction(Settings.ACTION_SETTINGS);
////                                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
//                                        startActivity(intent);     //跳转到设置界面
//                                    }

//                                    openApp(cmdOne, cmdTwo, startActivity.this);
                                }catch (Exception e){
//                                    callMenu.toast(startActivity.this,"请检查是否安装完整！");
                                    ToastUtil.showMessageApp(context,"请检查是否安装完整！");
                                }

                            }else{
                                if(imgId==R.mipmap.menu1_off){
                                    iv.setImageResource(R.mipmap.menu1_on);
                                }else if(imgId==R.mipmap.menu2_off){
                                    iv.setImageResource(R.mipmap.menu2_on);
                                }else if(imgId==R.mipmap.menu3_off){
                                    iv.setImageResource(R.mipmap.menu3_on);
                                }else if(imgId==R.mipmap.menu4_off){
                                    iv.setImageResource(R.mipmap.menu4_on);
                                }else if(imgId==R.mipmap.menu5_off){
                                    iv.setImageResource(R.mipmap.menu5_on);
                                }else if(imgId==R.mipmap.menu6_off){
                                    iv.setImageResource(R.mipmap.menu6_on);
                                }
                            }



//                            write(bytes);   //TODO  发送串口指令
//                            boolean isSendy = uartJnit.getInstance().sendCmds(cmd); //TODO

                            return true;

                        }
                    });
                }

            }else if("mcv".equals(type)){    //MiClockView 加载小米时钟，用于屏保
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int bgColor = (int)obj[4];  //屏保时钟界面背景

                miClockView = new MiClockView(context, (int)obj[5], (int)obj[6], (int)obj[7], (int)obj[8], (int)obj[9]);
                miClockView.setBackgroundColor(bgColor);

                v.addView(miClockView, params);

                miClockView.setVisibility(View.GONE);

                //屏保界面触摸事件，触摸界面就能关闭屏保界面，回到之前界面
                miClockView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        Log.e("mcv===onTouch", "===");

                        miClockView.setVisibility(View.GONE);
                        return false;
                    }
                });
            }else if("sv".equals(type)){    //SpeedView 加载码表，用于屏保
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int bgColor = (int)obj[4];  //屏保时钟界面背景
                svCmd = (String)obj[8];

                speedView = new SpeedView(context, (int)obj[5], (int)obj[6], (int)obj[7]);
                speedView.setBackgroundColor(bgColor);

                v.addView(speedView, params);

                speedView.setVisibility(View.GONE);
                speedView.setmSpeed(0);

                //屏保界面触摸事件，触摸界面就能关闭屏保界面，回到之前界面
                speedView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        Log.e("sv===onTouch", "===");

                        speedView.setVisibility(View.GONE);
                        return false;
                    }
                });
            }else if("lrsv".equals(type)){  //加载导航转盘，用于切换显示区
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                String[] names = (String[])obj[2];   //导航转盘的每个item名称
                int textSize = (int)obj[3];   //导航转盘的每个item文字大小
                int textColor = (int)obj[4];   //导航转盘的每个item文字颜色

                LoopRotarySwitchView mLoopRotarySwitchView = new LoopRotarySwitchView(this);
                mLoopRotarySwitchView.setGravity(Gravity.CENTER);   //导航转盘里的内容居中

                //加载导航转盘的所有item
                for (int j = 0; j < names.length; j++) {
                    TextView tv=new TextView(this);
                    tv.setText(names[j]);
                    tv.setTextSize(textSize);
                    tv.setTextColor(textColor);
                    mLoopRotarySwitchView.addView(tv);
                }

                v.addView(mLoopRotarySwitchView, params);

                mLoopRotarySwitchView
                        .setR(270)  //设置导航转盘半径的大小
//                      .setAutoRotation(false)//是否自动切换
//                      .setAutoScrollDirection(LoopRotarySwitchView.AutoScrollDirection.left)//切换方向
//                      .setAutoRotationTime(2000)//自动切换的时间  单位毫秒
                        .setLoopRotationX(7);   //设置导航转盘X方向倾斜度 7度

                //导航栏item点击事件
                mLoopRotarySwitchView.setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void selected(int position, View view) {

                        curPos = position;

                        Log.e("selected===", isEnd+"==="+pos+"==="+position+"==="+toPos+"==="+dx);

                        if(dx!=0){
                            long time = 0;

                            if(dx<0.1 && dx>-0.1){
                                Log.e("selected>>>1", isEnd+"==="+pos+"==="+position+"==="+dx+"==="+time);

                                framelayout.setAlpha(1);
                                framelayout2.setAlpha(1);

                                isStop = true;

                                FragmentManager manager = getSupportFragmentManager();
                                manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                                manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                                FragmentTransaction tration = manager.beginTransaction();
                                tration.addToBackStack(Fragment_First.TAG);
                                tration.addToBackStack(Fragment_Second.TAG);



                                for (int i=0; i<frags.length; i++){
                                    if(position==i){
                                        tration.replace(id2, frags[i], Fragment_Second.TAG);
                                        toFrag = frags[i];
                                        toPos = i;
                                    }
                                }

                                tration.commit();

                                pos = position;
                                dx = 0;
                                first = true;
                                isEnd = false;
                            }else{
                                if(dx>=0.1){
                                    time = (long)(1000*(1-dx));
                                }else{
                                    time = (long)(1000*(1+dx));
                                }
                            }

                            //纠正最终定，智能判断要不要纠正
                            handler.postDelayed(new Runnable(){
                                public void run() {

                                    Log.e("selected===1", isEnd+"==="+pos+"==="+position+"==="+dx+"==="+(toFrag instanceof Fragment_First)+"==="+(toFrag instanceof Fragment_Second)+"==="+(toFrag instanceof Fragment_Third));


                                    if(position==toPos){

                                        Log.e("selected===3", isEnd+"==="+pos+"==="+position+"==="+dx+"==="+(fromFrag instanceof Fragment_First)+"==="+(fromFrag instanceof Fragment_Second)+"==="+(fromFrag instanceof Fragment_Third));

                                    }else{
                                        Log.e("selected===4", isEnd+"==="+pos+"==="+position+"==="+dx+"==="+(fromFrag instanceof Fragment_First)+"==="+(fromFrag instanceof Fragment_Second)+"==="+(fromFrag instanceof Fragment_Third));


                                        isStop = true;

                                        FragmentManager manager = getSupportFragmentManager();
                                        manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                                        manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                                        FragmentTransaction tration = manager.beginTransaction();
                                        tration.addToBackStack(Fragment_First.TAG);
                                        tration.addToBackStack(Fragment_Second.TAG);

                                        for (int i=0; i<frags.length; i++){
                                            if(position==i){
                                                tration.replace(id2, frags[i], Fragment_Second.TAG);
                                                toFrag = frags[i];
                                                toPos = i;
                                            }
                                        }

                                        framelayout.setAlpha(0);
                                        framelayout2.setAlpha(1);

                                        tration.commit();

                                    }

                                    pos = position;
                                    dx = 0;
                                    first = true;
                                    isEnd = false;
                                }
                            }, time);


                        }else{

                            Log.e("selected===2", isEnd+"==="+pos+"==="+position+"==="+dx+"==="+toPos);

                            isEnd = true;

                            if(pos==0 && position==0){
                                FragmentManager manager = getSupportFragmentManager();
                                manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                                manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                                FragmentTransaction tration = manager.beginTransaction();
                                tration.addToBackStack(Fragment_First.TAG);
                                tration.addToBackStack(Fragment_Second.TAG);

                                Log.e("selected===3", isEnd+"==="+pos+"==="+position+"==="+dx+"==="+toPos+"==="+id2+"==="+frags[0]);

                                tration.replace(id2, frags[0], Fragment_Second.TAG);
                                toFrag = frags[0];
                                toPos = 0;

                                framelayout.setAlpha(0);
                                framelayout2.setAlpha(1);

                                tration.commit();
                            }else{
                                for (int i=0; i<frags.length; i++){
                                    if(pos==i && position==(i+1)%frags.length){
                                        applyRotation(true, frags[i], frags[(i+1)%frags.length], pos, position);
                                    }else if(pos==i && position==(i-1+frags.length)%frags.length){
                                        applyRotation(false, frags[i], frags[(i-1+frags.length)%frags.length], pos, position);
                                    }
                                }
                            }

                            pos = position;

                            first = true;
                            isEnd = false;
                        }

                    }
                });

                //导航栏触摸事件
                mLoopRotarySwitchView.setOnLoopViewTouchListener(new OnLoopViewTouchListener() {
                    @Override
                    public void onTouch(MotionEvent event) {

                        if(event.getAction()==0){
                            isStop = false;
                        }

                        Log.e("onTouch===0", first+"==="+isEnd+"==="+dx+"==="+x+"==="+event.getX()+"==="+event.getY()+"==="+event.getAction());

                        if(first){


                            x = event.getX();
                            first = false;

                        }

                        if(isEnd){
                            return;
                        }

                        dx = (x-event.getX())/200;



                        Log.e("onTouch===", pos+"==="+dx+"==="+x+"==="+event.getX()+"==="+event.getY()+"==="+event);


                        if(event.getAction()==1){   //手指离开屏幕
                            isEnd = true;
                            first = true;

                            left_first = true;

                        }else{
                            isEnd = false;
                        }

//                        if(dx<0.1 && dx>-0.1){
//                            return;
//                        }

                        if(dx>0.1){
                            Log.e("onTouch===1", isEnd+"==="+dx+"==="+pos);

                            for (int i=0; i<frags.length; i++){
                                if(pos==i){
                                    applyRotation(true, frags[i], frags[(i+1)%frags.length], i, (i+1)%frags.length);
                                }
                            }

                            degrees = Util_Rotate3DAnimation2.degrees;
                            degrees2 = Util_Rotate3DAnimation2.degrees2;
                        }else if(dx<-0.1){
                            Log.e("onTouch===2", isEnd+"==="+dx+"==="+pos);

                            for (int i=0; i<frags.length; i++){
                                if(pos==i){
                                    applyRotation(false, frags[i], frags[(i-1+frags.length)%frags.length], i, (i-1+frags.length)%frags.length);
                                }
                            }

                            degrees = Util_Rotate3DAnimation2.degrees;
                            degrees2 = Util_Rotate3DAnimation2.degrees2;
                        }



                        Log.e("onTouch===3", isEnd+"==="+dx+"==="+degrees+"==="+degrees2+"==="+mLoopRotarySwitchView.getSelectItem()+"==="+event.getX()+"==="+event.getY()+"==="+event.getAction());


                    }
                });

            }else if("fl".equals(type)){    //显示区
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                framelayout = new FrameLayout(this);
                framelayout.setId(id);  //给每个framelayout设置ID，用于旋转逻辑
                v.addView(framelayout, params);

                framelayout2 = new FrameLayout(this);
                framelayout2.setId(id2);
                v.addView(framelayout2, params);

            }
        }

    }

    //轮循更新温度、时间、日期、屏保时钟
    private void loop(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                long n=0;

                while (true){

                    m_myHandler.sendEmptyMessage(1);    //更新温度、时间、日期

                    try {
                        Thread.sleep(loopTime);     //轮循时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    n++;

                    if(n%cn==0){
                        m_myHandler.sendEmptyMessage(2);    //显示屏保时钟
                    }

                }

            }
        }).start();
    }

    //轮循所用Handler，android传递消息的机制
    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    break;

                case 1:
                    //获取当前时间
                    Date date = new Date(System.currentTimeMillis());
                    String time1 = simpleDateFormat.format(date);
                    String time2 = simpleDateFormat2.format(date);

                    Log.d("m_myHandler===1", "==="+bytes_temp);


                    //串口读取车内温度
//                    read(bytes_temp);     //TODO
//                    int read_count = uartJni.read(fd, read_buf, read_buf.length);   //TODO

                    readFeedback();

//                    tv_temp.setText("25℃");
                    tv_time.setText(time1);
                    tv_date.setText(time2);


                    break;

                case 2:
                    speedView.setVisibility(View.VISIBLE);
                    break;

                default:
                    break;
            }
            return false;
        }
    });


    private void addDataReceiver() {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("com.unibroad.candata.send");
//        mFilter.addAction("com.unibroad.candata.receive");
        registerReceiver(dataReceiver, mFilter);
    }

    private BroadcastReceiver dataReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equals("com.unibroad.candata.send")) {
                        String data = intent.getStringExtra("cmd"); //2e 10 0a 01 D0  00 00 ffffff3f00714d
                        byte[] bytes = hexStringToByte(data);
                        Log.e("onReceive===", bytes+"===" + data);

//                        byte b1 = getCheckCanboxByte(new byte[]{0x2E, (byte)0x10, 0x0A, (byte)0xeb, 0x00, 0x00, 0x00, (byte)0xff, (byte)0xff, (byte)0xff, 0x3f, 0x00, (byte) 0x71});
//                        Log.e("onReceive===1", "===" + b1);

                        byte[] readCmd = new byte[bytes[2]+4];
                        readCmd[0] = 0x5A;
                        readCmd[1] = (byte)0xA5;
                        readCmd[2] = (byte)(bytes[2]+1);
                        readCmd[3] = (byte)0x82;
                        for(int i=4; i<bytes[2]+2; i++){
                            readCmd[i] = bytes[i+1];
                        }
                        readCmd[bytes[2]+2] = 0x00;
                        readCmd[bytes[2]+3] = 0x00;

                        String s = toHex(readCmd, readCmd.length);
                        Log.e("onReceive===1", s + "===" + readCmd.length);

                        s = "5aa50782f00300010000";
                        readFeedback(s);

                        //TODO 从can过来的数据接收处理演示
//                strbuffer.append(">>>>接收：").append(data).append("     ");
//                data_tv.setText(strbuffer);
//                sendData(new byte[]{0x2E, (byte) 0x88, 0x0A, (byte) 0xAA, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, 0x5D});
//                        byte[] bb = new byte[]{0x2E, (byte) 0x88, 0x0A, (byte) 0xAA, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88};
//                        byte b = getCheckCanboxByte(bb);
//                        Log.e("onReceive===2", "===" + b);
//                        sendData(new byte[]{0x2E, (byte) 0x88, 0x0A, (byte) 0xAA, 0x02, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, b});
                    }
        }
    };

    public void sendData(byte[] buffer) {
        Log.e("sendData===", "===" + buffer);
        String data = byteArrayToHexString(buffer);
        Log.e("sendData===1", "===" + data);
        Intent intent = new Intent();
        intent.setAction("com.unibroad.candata.receive");
        intent.putExtra("cmd", data);
        sendBroadcast(intent);
//
//        //数据发送演示
//        strbuffer.append(">>>>发送：").append(data).append("\n");
//        data_tv.setText(strbuffer);
    }

    private byte getCheckCanboxByte(byte[] buffer) {
        int lenght = buffer.length;
        byte check = 0;//buffer[1];
        for (int i =1; i < lenght; i++) {
            check += buffer[i];
        }

        Log.e("getCheckCanboxByte==", "===" + check);

//        return check;
        return (byte) (check ^ 0xff);
    }

//    协议ID号:app->CAN : 0x88
//    协议ID号:CAN->app : 0x10

//    byte[]{0x2E(协议头固定), (byte) 0x88(协议ID号),
//            0x0A(长度位),
//            0x00, 0x00, 0x00, 0x00,
//            0x00, 0x00, 0x00, 0x00,
//            0x00, 0x00,
//            0x00(检验位)}

    /**
     * 字符串转Byte数组工具
     * @param hex
     * @return
     */
    private static byte[] hexStringToByte(String hex) {

        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }
    /**
     *  Byte数组转字符串工具
     * @param byteArray
     * @return
     */
    private static String byteArrayToHexString(byte[] byteArray) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (byteArray == null || byteArray.length <= 0) {
            return null;
        }
        for (int i = 0; i < byteArray.length; i++) {
            int v = byteArray[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }



    byte[] read_buf = new byte[10*1024];
    Runnable runnable = new Runnable(){
        @Override
        public void run() {
//            readFeedback();
        }
    };

    //读取并解析指令
    public int readFeedback() {
        String tmpstr = "";
        String feedCamdstr = "";
        String feedCamdFalgstr = "";
        try {
            Log.d("readFeedback===00", fd+"==="+read_buf);

            int read_count = uartJni.read(fd, read_buf, read_buf.length);

            Log.d("readFeedback===0", read_count+"==="+toHex(read_buf, read_count));

//            if (read_count < 0) {
//                read_count = 0;
//            }
//            if (read_count > 60) {
//                read_count = 60;
//            }
            tmpstr = toHex(read_buf, read_count).toString();

            Log.d("readFeedback===", PageS.feedType+"==="+tmpstr);

        } catch (Exception ex) {
        }
        if (!tmpstr.equals("")) {

            int index, index82, index5a;
            int cmdlenght;
            int tmpstrlenght = read_buf.length;

            for (String key : PageS.feedType.keySet()) {
                Log.e("key===", "===" + key);

                if("0000".equals(key)) continue;

                index = tmpstr.indexOf(key);
                if (index >= 8) {
                    index = index-8;
                    if (index != -1) {
                        cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;

                        Log.e("readFeedback===1", index+"==="+cmdlenght);

                        if(tmpstr.length()<index + (cmdlenght + 3) * 2) continue;

                        feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);

                        Log.e("readFeedback===2", feedCamdstr+"==="+tmpstr);

                        Message cmdmsg = new Message();
                        cmdmsg.what = 20;
                        Bundle bcmd = new Bundle();
                        bcmd.putString("alltext", feedCamdstr);
                        cmdmsg.setData(bcmd);
                        boolean xx = uHandler.sendMessage(cmdmsg);
                    }
                }
            }

        }
        return 1;
    }

    //读取并解析指令
    public int readFeedback(String tmpstr) {
//        String tmpstr = "";
        String feedCamdstr = "";
        String feedCamdFalgstr = "";
        try {
//            Log.e("readFeedback===00", fd+"==="+read_buf);
//
//            int read_count = uartJni.read(fd, read_buf, read_buf.length);
//
//            Log.e("readFeedback===0", read_count+"==="+toHex(read_buf, read_count));

//            if (read_count < 0) {
//                read_count = 0;
//            }
//            if (read_count > 60) {
//                read_count = 60;
//            }
//
//            tmpstr = toHex(read_buf, read_count).toString();

            Log.e("readFeedback===", PageS.feedType+"==="+tmpstr);

        } catch (Exception ex) {
        }
        if (!tmpstr.equals("")) {

            int index, index82, index5a;
            int cmdlenght;
            int tmpstrlenght = read_buf.length;

//            index = tmpstr.indexOf("82");

            for (String key : PageS.feedType.keySet()) {
                Log.e("key===", "===" + key);

                if("0000".equals(key)) continue;

                index = tmpstr.indexOf(key);
                if (index >= 8) {
                    index = index-8;
                    if (index != -1) {
                        cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;

                        Log.e("readFeedback===1", index+"==="+cmdlenght);

                        if(tmpstr.length()<index + (cmdlenght + 3) * 2) continue;

                        feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);

                        Log.e("readFeedback===2", feedCamdstr+"==="+tmpstr);

                        Message cmdmsg = new Message();
                        cmdmsg.what = 20;
                        Bundle bcmd = new Bundle();
                        bcmd.putString("alltext", feedCamdstr);
                        cmdmsg.setData(bcmd);
                        boolean xx = uHandler.sendMessage(cmdmsg);
                    }
                }
            }


//            cmdmsg = new Message();
//            cmdmsg.what = 20;
//
//            index = tmpstr.indexOf("1010");
//            if (index >= 8) {
//                index = index-8;
//                if (index != -1) {
//                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
//
//                    Log.e("readFeedback===1", index+"==="+cmdlenght);
//
//                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
//
//                    Log.e("readFeedback===2", feedCamdstr+"==="+tmpstr);
//
//                    bcmd.putString("alltext", feedCamdstr);
//                    cmdmsg.setData(bcmd);
//                    boolean xx = uHandler.sendMessage(cmdmsg);
//                }
//            }
//
//            index = tmpstr.indexOf("f003");
//            if (index >= 8) {
//                index = index-8;
//                if (index != -1) {
//                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
//
//                    Log.e("readFeedback===1", index+"==="+cmdlenght);
//
//                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
//
//                    Log.e("readFeedback===2", feedCamdstr+"==="+tmpstr);
//
//                    bcmd.putString("alltext", feedCamdstr);
//                    cmdmsg.setData(bcmd);
//                    boolean xx = uHandler.sendMessage(cmdmsg);
//                }
//            }

        }
        //   handler.postDelayed(runnable, 100);
        return 1;
    }

    @SuppressLint("HandlerLeak")
    public Handler uHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 20:
                    String commandTxt = msg.getData().getString("alltext");

                    Log.e("uHandler===1", "==="+commandTxt);

//                    testtView.setText(commandTxt);
                    if (commandTxt.length() > 10) {
                        try {
                            refreshallui(commandTxt);     //5aa509821010000000007a5b
                        } catch (Exception ex) {
                            return;
                        }

                    }
                    break;
                default:
                    break;
            }
        }
    };

    //根据反馈指令，刷新所有ui
    private void refreshallui(String comingdata) {
        Log.e("refreshallui===", checkability(comingdata)+"==="+comingdata);

        if (!checkability(comingdata)) {
            return;
        }
        String message = "";
        if (comingdata.length() >= 40) {
            message = comingdata.substring(0, 40);
        } else {
            message = comingdata;
        }
        String firstFour = "";
        if ((message.length()) > 4) {
            firstFour = message.substring(0, 4);
        }
        int positionInBoard = 0;
        int counts = 0;
        if (message.length() > 19) {
            int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
            counts = (msgcounts - 7) / 2 + 1;
            String[] feedDevice = new String[counts];
            String[] feedStatus = new String[counts];

            Log.e("refreshallui===1", counts+"==="+PageS.feedType);

            if (counts == 1) {
                String feedDevicex = message.substring(8, 12);
                String deviceStaus = message.substring(12, 16);
                Message msg = new Message();
                String ntype = PageS.feedType.get(feedDevicex);

                Log.e("refreshallui===1_1", counts+"==="+ntype+"==="+feedDevicex+"==="+deviceStaus);

                msg.what = Integer.parseInt(ntype);
                Bundle bundle = new Bundle();
                bundle.putString("feedDevice", feedDevicex);
                bundle.putString("feedStatus", deviceStaus);
                msg.setData(bundle);
                if (feedOK(feedDevicex)) {
                    PageS.feedMap.put(feedDevicex, deviceStaus);
                }
                mHandler.sendMessage(msg);
            } else {
                for (int cc = 0; cc < counts; cc++) {
                    feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                    feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                    Log.e("refreshallui===2", counts+"==="+cc+"==="+feedDevice[cc]+"==="+feedStatus[cc]);

                    Message msg = new Message();
                    String ntype = PageS.feedType.get(feedDevice[cc]);

                    Log.e("refreshallui===3", counts+"==="+cc+"==="+ntype+"==="+feedDevice[cc]+"==="+feedStatus[cc]);

                    msg.what = Integer.parseInt(ntype);
                    Bundle bundle = new Bundle();
                    bundle.putString("feedDevice", feedDevice[cc]);
                    bundle.putString("feedStatus", feedStatus[cc]);
                    msg.setData(bundle);

                    Log.e("refreshallui===4", counts+"==="+cc+"==="+ntype+"==="+feedDevice[cc]+"==="+feedStatus[cc]+"==="+feedOK(feedDevice[cc]));

//                    if (feedOK(feedDevice[cc])) {
//                        PageS.feedMap.put(feedDevice[cc], feedStatus[cc]);
//                    }

                    mHandler.sendMessage(msg);
                }
            }
        }
    }

    private boolean checkability(String comingdata) {
        boolean result = false;
        try {
            int alllength = comingdata.length() - 3;
            String firstFour = "";
            if ((comingdata.length()) > 4) {
                firstFour = comingdata.substring(0, 4);
                if (firstFour.equals(headerData)) {
                    int msgcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                    if (alllength == (msgcounts * 2 + 3)) {
                        result = true;
                    }
                }
            }
        } catch (Exception ex) {
            result = false;
        }
        return result;
    }

    public boolean feedOK(String entr) {
        String[] tmpAll = new String[]{"0071", "0072", "0073", "0074", "0075", "0076", "0081", "0082", "0099", "0099", "0099", "0086", "0087", "1010", "1011", "71b0", "72b0", "73b0"};
        return TransformUtils.isAvail(tmpAll, entr);
    }


    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
//                case 1:
//                    Log.e("mHandler===", "==="+(String) msg.obj);
//
////                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, null);
////                    JPushInterface.setAlias(context, 1, (String) msg.obj);
//                    break;
//
//                case 2:
//                    JPushInterface.setAliasAndTags(getApplicationContext(), null, (Set<String>) msg.obj, null);
////                    JPushInterface.setT
//                    break;

                case 1://开关反馈
                    // int myPosition = TransformUtils.findPosition(PageS.feedDArray, myDevice);
                    // if (myPosition != -1) {
                    String myDevice = msg.getData().getString("feedDevice");
                    String myStatus = msg.getData().getString("feedStatus");

                    Log.e("mHandler===", myDevice+"==="+myStatus);

                    if(myDevice.equals(svCmd)){    //6003

//                        int speed = Integer.parseInt(myStatus);

                        int fir = Integer.parseInt(CRC16.convert16(myStatus.substring(2, 3)));
                        int sec = Integer.parseInt(CRC16.convert16(myStatus.substring(3)));
                        int speed = fir * 16 + sec;

//                        tv_temp.setText(temp+"℃");
//
//                        if(temp>22){
//                            tv_temp.setText("HI");
//                        }else if(temp<18){
//                            tv_temp.setText("LO");
//                        }

//                        speedView.setVisibility(View.VISIBLE);  //TODO
                        speedView.setmSpeed(speed);

                    }else{
                        Intent intent = new Intent("carcontrol.broadcast.action");
                        intent.putExtra("feedDevice", myDevice);
                        intent.putExtra("feedStatus", myStatus);
                        context.sendBroadcast(intent);
                    }



//                    int picId =feedPicID.get(myDevice);
//                    int icoId =feedIconID.get(myDevice);
//
//                    Log.e("mHandler===1", myDevice+"==="+myStatus+"==="+picId+"==="+icoId);

//                    if( (picId != -1)&&(icoId != -1)){
//                        boolean fstt = myStatus.equals("0001") ? true:false;
////                        newm.touchFlag=false;
//
//                        Log.e("mHandler===1_1", fstt+"==="+picId+"==="+icoId);
//
//                        testFeed(picId, icoId, fstt);
//                    }
                    break;

//                case 2://在收到消息时，电压显示界面
//                    String myDevicex = msg.getData().getString("feedDevice");
//                    String myStatusx = msg.getData().getString("feedStatus");
//
//                    Log.e("mHandler===2", myDevicex+"==="+myStatusx);
//
//                    disv(myDevicex, myStatusx);
//
//                    break;
//                case 3://界面切换
//                    String[] src = {"0","1","2","3","4","5","6","7","8","9","10","11"};
//                    //通过 Bundle传过来
//                    String jmppageno = msg.getData().getString("jmppageno");
//
//                    Log.e("mHandler===3", "==="+jmppageno);
//
//                    if("applicationlist".equals(jmppageno)){
//                        Intent intent=new Intent(context, gActivity.class);
//                        startActivity(intent);
//                    }else if("controlcenter".equals(jmppageno)){
//                        refreshui(2);
//                    }else{
//                        if(isInteger(jmppageno)){
//                            int myjmpposition = Integer.parseInt(jmppageno);
//
//                            //    if(myjmpposition>=0 && myjmpposition<20){
//                            if((myjmpposition & 0x01) == 0){
//                                refreshui(myjmpposition);
//                            }
//                        }else{
//                            try {
//                                Intent intent = getPackageManager().getLaunchIntentForPackage(jmppageno);
//                                startActivity(intent);
//                            }catch (Exception e){
//                                callMenu.toast(MainActivity.this,"请检查是否安装完整！");
//                            }
//
//                        }
//                    }
//
//                    break;

                default:
            }
        }
    };

    //是否是数字型字符串
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    private void openApp(String packageName, String actName) {

        Intent intent=new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(new ComponentName(packageName, actName));
        startActivity(intent);


    }

    //根据反馈是否开关，更新图标背景
//    private  void testFeed(int picId1, int icoId1, boolean onff){
//        //if((picId1 == PageS.pageno)&& (picId1 != -1)&&(icoId1 != -1)) {
//        if((picId1 != -1)&&(icoId1 != -1)) {
//            MeziView newm = (MeziView) frame.getChildAt(icoId1);
//            //String aaaa = newm.getId() + "|" + myPosition;
//            //   Log.e("feedTest", aaaa);
//            if (newm != null) {
////                if (bitmap != null)
//
//                if (onff) {
//                    if(picId1 == PageS.pageno){
//                        newm.mResBitmap = PageS.page[picId1].icon[icoId1].iconbj;
//                        newm.mRect = PageS.page[picId1].icon[icoId1].iconRect;
//                    }
//                    PageS.page[picId1].icon[icoId1].isfeedBack= true;
//                } else {
//                    if(picId1 == PageS.pageno){
//                        newm.mResBitmap = PageS.page[picId1].icon[icoId1].iconqj;
//                        newm.mRect = PageS.page[picId1].icon[icoId1].iconRect;
//                    }
//                    PageS.page[picId1].icon[icoId1].isfeedBack= false;
//                }
//
//                MeziView.fristFlag = false;
//                newm.repaint();
//
//                Log.e("testFeed===", picId1+"==="+icoId1+"==="+onff+"==="+pid);
//
//                if(!"".equals(pid)){
//                    sendMessage(pid,"receive@"+picId1+"@"+icoId1+"@"+onff+"@");     //7寸屏向手机发receive反馈信号，使7寸屏和手机界面图标显示同步
//                }
//
//            }
//        }
//    }

    //显示区3D旋转切换，当前界面和目的界面能同时显示
    public void applyRotation(final boolean zheng, Fragment fromFragment, Fragment toFragment, int fromPosition, int toPosition) {
        fromFrag = fromFragment;
        toFrag = toFragment;
        toPos = toPosition;

        float centerX;
        float centerY;
        float start;
        float end;

        if(dx==0){
            if(zheng){
                FragmentManager manager = getSupportFragmentManager();
                manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                FragmentTransaction tration = manager.beginTransaction();
                tration.addToBackStack(Fragment_First.TAG);
                tration.addToBackStack(Fragment_Second.TAG);
                tration.replace(id, fromFragment, Fragment_First.TAG).replace(id2, toFragment, Fragment_Second.TAG).commit();

                if(toFragment instanceof Fragment_First){
                    Log.e("tration===0", tration.isEmpty()+"===");
                }else{

                }

                //当前页逐渐关闭
                centerX = width;
                centerY = 0;
                start = 0;
                end = -90;

                Log.e("applyRotation===2", "==="+centerX+"==="+centerY+"==="+framelayout.getWidth()+"==="+framelayout.getHeight());

                // Create a new 3D rotation with the supplied parameter
                // The animation listener is used to trigger the next animation
                Util_Rotate3DAnimation2 rotation2 = new Util_Rotate3DAnimation2(framelayout, width, dx, start, end, centerX, centerY, 0.0f, zheng, false, isEnd);
                rotation2.setDuration(1000);
                rotation2.setFillAfter(true);
                rotation2.setInterpolator(new AccelerateInterpolator());
                framelayout.startAnimation(rotation2);


                //下一页逐渐显示
                centerX = 0;
                centerY = 0;
                start = 30;
                end = 0;

                Log.e("applyRotation===", isEnd+"==="+dx+"==="+degrees+"==="+centerX+"==="+centerY+"==="+framelayout.getWidth()+"==="+framelayout.getHeight());

                Util_Rotate3DAnimation2 rotation = new Util_Rotate3DAnimation2(framelayout2, width, dx, start, end, centerX, centerY, 0.0f, zheng, true, isEnd);
                rotation.setDuration(1000);
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                framelayout2.startAnimation(rotation);

                Log.e("applyRotation===1", isEnd+"==="+dx+"==="+degrees2+"==="+centerX+"==="+centerY+"==="+framelayout.getWidth()+"==="+framelayout.getHeight());


            }else{
                //当前页逐渐关闭
                FragmentManager manager = getSupportFragmentManager();
                manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                FragmentTransaction tration = manager.beginTransaction();
                tration.addToBackStack(Fragment_First.TAG);
                tration.addToBackStack(Fragment_Second.TAG);
                tration.replace(id, fromFragment, Fragment_First.TAG).replace(id2, toFragment, Fragment_Second.TAG).commit();

                Log.e("tration===", tration.isEmpty()+"===");

                centerX = 0;
                centerY = 0;
                start = 0;
                end = 90;

                Log.e("applyRotation===", isEnd+"==="+dx+"==="+degrees+"==="+centerX+"==="+centerY+"==="+framelayout.getWidth()+"==="+framelayout.getHeight());

                Util_Rotate3DAnimation2 rotation = new Util_Rotate3DAnimation2(framelayout, width, dx, start, end, centerX, centerY, 0.0f, zheng, true, isEnd);
                rotation.setDuration(1000);
                rotation.setFillAfter(true);
                rotation.setInterpolator(new AccelerateInterpolator());
                framelayout.startAnimation(rotation);


                Log.e("applyRotation===1", isEnd+"==="+dx+"==="+degrees2+"==="+centerX+"==="+centerY+"==="+framelayout2.getWidth()+"==="+framelayout2.getHeight());

                //下一页逐渐显示
                centerX = width;
                centerY = 0;
                start = -30;
                end = 0;

                Util_Rotate3DAnimation2 rotation2 = new Util_Rotate3DAnimation2(framelayout2, width, dx, start, end, centerX, centerY, 0.0f, zheng, false, isEnd);
                rotation2.setDuration(1000);
                rotation2.setFillAfter(true);
                rotation2.setInterpolator(new AccelerateInterpolator());
                framelayout2.startAnimation(rotation2);
            }

        }else if(dx>0){       //右转
            Log.e("right===", left_first+"==="+isEnd);

            if((left_first && !isEnd) || toPos!=toPos2){
                left_first = false;
                toPos2 = toPos;

                FragmentManager manager = getSupportFragmentManager();
                manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                FragmentTransaction tration = manager.beginTransaction();
                tration.addToBackStack(Fragment_First.TAG);
                tration.addToBackStack(Fragment_Second.TAG);
                tration.replace(id, fromFragment, Fragment_First.TAG).replace(id2, toFragment, Fragment_Second.TAG).commit();

                if(toFragment instanceof Fragment_First){
                    Log.e("tration===0", tration.isEmpty()+"===");
                }else if(toFragment instanceof Fragment_Second){
                    Log.e("tration===1", tration.isEmpty()+"===");
                }else if(toFragment instanceof Fragment_Third){
                    Log.e("tration===2", tration.isEmpty()+"===");
                }
            }

            //当前页逐渐关闭
            centerX = width;
            centerY = 0;
            start = isEnd?degrees2:0;
            end = -90;
            dx = dx>1?1:dx;

            Log.e("applyRotation===", "==="+centerX+"==="+centerY+"==="+framelayout.getWidth()+"==="+framelayout.getHeight());

            Util_Rotate3DAnimation2 rotation2 = new Util_Rotate3DAnimation2(framelayout, width, dx, start, end, centerX, centerY, 0.0f, zheng, false, isEnd);
            rotation2.setDuration((long)(1000*(1-dx)));
            rotation2.setFillAfter(true);
            rotation2.setInterpolator(new AccelerateInterpolator());
            framelayout.startAnimation(rotation2);


            Log.e("applyRotation===1", isEnd+"==="+dx+"==="+degrees2);

            //下一页逐渐显示
            centerX = 0;
            centerY = 0;
            start = isEnd?degrees:30;
            end = 0;

            Log.e("applyRotation===2", isEnd+"==="+dx+"==="+degrees);

            // Create a new 3D rotation with the supplied parameter
            // The animation listener is used to trigger the next animation
            Util_Rotate3DAnimation2 rotation = new Util_Rotate3DAnimation2(framelayout2, width, dx, start, end, centerX, centerY, 0.0f, zheng, true, isEnd);
            rotation.setDuration((long)(1000*(1-dx)));
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            framelayout2.startAnimation(rotation);

        }else if(dx<0){  //左转
            //当前页逐渐关闭
            Log.e("left===", left_first+"==="+isEnd);

            if((left_first && !isEnd) || toPos!=toPos2){
                left_first = false;
                toPos2 = toPos;

                FragmentManager manager = getSupportFragmentManager();
                manager.popBackStackImmediate(Fragment_First.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                manager.popBackStackImmediate(Fragment_Second.TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                FragmentTransaction tration = manager.beginTransaction();
                tration.addToBackStack(Fragment_First.TAG);
                tration.addToBackStack(Fragment_Second.TAG);
                tration.replace(id, fromFragment, Fragment_First.TAG).replace(id2, toFragment, Fragment_Second.TAG).commit();

                Log.e("tration===", tration.isEmpty()+"===");
            }

            centerX = 0;
            centerY = 0;
            start = isEnd?-degrees:0;;
            end = 90;

            dx = dx<-1?-1:dx;

            Log.e("applyRotation===", isEnd+"==="+dx+"==="+degrees+"==="+centerX+"==="+centerY+"==="+framelayout.getWidth()+"==="+framelayout.getHeight());

            Util_Rotate3DAnimation2 rotation = new Util_Rotate3DAnimation2(framelayout, width, dx, start, end, centerX, centerY, 0.0f, zheng, true, isEnd);
            rotation.setDuration((long)(1000*(1+dx)));
            rotation.setFillAfter(true);
            rotation.setInterpolator(new AccelerateInterpolator());
            framelayout.startAnimation(rotation);


            Log.e("applyRotation===1", isEnd+"==="+dx+"==="+degrees2+"==="+centerX+"==="+centerY+"==="+framelayout2.getWidth()+"==="+framelayout2.getHeight());

            //下一页逐渐显示
            centerX = width;
            centerY = 0;
            start = isEnd?degrees2:-30;
            end = 0;

            Util_Rotate3DAnimation2 rotation2 = new Util_Rotate3DAnimation2(framelayout2, width, dx, start, end, centerX, centerY, 0.0f, zheng, false, isEnd);
            rotation2.setDuration((long)(1000*(1+dx)));
            rotation2.setFillAfter(true);
            rotation2.setInterpolator(new AccelerateInterpolator());
            framelayout2.startAnimation(rotation2);
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
//            customBuilder.setTitle("温馨提示").setMessage("您将退出CarControl。")
//                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.cancel();
//                        }
//                    }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.cancel();
//                    AppManager.getAppManager().AppExit(context);
//                }
//            });
//            customBuilder.create().show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
